/*
 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     bstefanescu
 */
package org.nuxeo.gwt.habyt.app.client.form.bindings;

import java.io.Serializable;
import java.util.Date;

import org.nuxeo.gwt.habyt.app.client.form.FormControl;
import org.nuxeo.gwt.habyt.templates.client.bindings.Helper;
import org.nuxeo.gwt.habyt.templates.client.widgets.DateBox;

import com.google.gwt.dom.client.Element;
import com.google.gwt.i18n.client.DateTimeFormat;

/**
 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
 * 
 */
public class DateFactory extends AbstractControlFactory {

    public DateFactory() {
        super("date");
    }

    @Override
    protected FormControl createControl(Element element) {
        String value = element.getInnerText();
        String name = Helper.getAttribute(element, "name");
        if (name == null) {
            throw new IllegalArgumentException("Date control name is required");
        }
        String format = Helper.getAttribute(element, "format");

        DateTimeFormat fmt = format == null ? DateTimeFormat.getFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
                : DateTimeFormat.getFormat(format);
        DateBox db = new DateBox(fmt);
        db.setName(name);
        if (value != null && value.length() > 0) {
            db.setText(value);
        }
        return new FormControl(db) {
            @Override
            public String getName() {
                return ((DateBox) getWidget()).getName();
            }

            @Override
            public void setValue(Serializable value) {
                DateBox db = (DateBox) getWidget();
                if (value instanceof String) {
                    db.setText((String) value);
                } else if (value instanceof Date) {
                    db.setValue((Date) value);
                } else {
                    throw new IllegalArgumentException(
                            "Not supported date type: " + value);
                }
            }

            @Override
            public Serializable getValue() {
                return ((DateBox) getWidget()).getValue();
            }
        };

    }
}
